const jwt = require('jsonwebtoken')
const SECRET_KEY = 'login2021'
const db = require('../db/index')
// const manageDb = require('../db/manage')
const bcrypt = require('bcryptjs');

const verify = (req, source) => {
    const { authorization } = req.headers;
    const token = authorization.replace('Bearer', '').trim()

    return new Promise((resolve, reject) => {
        jwt.verify(token, SECRET_KEY, (err, decoded) => {
            if (err) {
                reject(err)
            } else {
                const sql = `select * from user where name=?`
                if (source == 'reception') {
                    const { username, password } = decoded.user
                    db.query(sql, username, (err, result) => {
                        if (err) {
                            reject(err)
                        } else {
                            const ps = `${password}`.trim();
                            const isMatch = bcrypt.compareSync(ps, result[0].password);
                            if (isMatch) {
                                resolve(decoded.user)
                            } else {
                                reject(new Error())
                            }
                        };
                    })
                } else {
                    const sql = `select * from administrators where name=?`
                    const { username, password } = decoded.user
                    // manageDb.query(sql, username, (err, result) => {
                    //     if (err) {
                    //         reject(err)
                    //     } else {
                    //         const ps = `${password}`.trim();
                    //         const isMatch = bcrypt.compareSync(ps, result[0].password);
                    //         if (isMatch) {
                    //             resolve(decoded.user)
                    //         } else {
                    //             reject(new Error())
                    //         }
                    //     };
                    // })
                }

            }

        });
    })
}

module.exports = { verify, jwt, SECRET_KEY }
